import $ from "./library/jquery.js";
let phonenum;
let username;
let password;

$("#phonenum").on("blur", function() {
    phonenum = $(this).val();
    let reg =
        /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    if (!reg.test(phonenum)) {
        $("#msg-login-box").prepend(
            "<div id='login-error'>手机号不存在，请重新输入</div>"
        );
        $("#phonenum").on("click", function() {
            $("#msg-login-box").children().remove("#login-error");
        });
    } else {
        $.ajax({
                type: "get",
                url: "../../interface/login-msg.php",
                data: { phonenum },
                dataType: "json",
            })
            .then((res) => {
                console.log(res);
                let randomnum = "";
                for (let i = 0; i < 6; i++) {
                    randomnum += Math.floor(Math.random() * 10);
                }
                console.log(randomnum);
                $("#msg-login-box").on("click", function() {
                    if (randomnum == $("#fm-smscode").val()) {
                        alert(`用户${res.username}登录成功！`);
                        location.href = `./index.html?username=${res.username}`;
                    }
                });
            })
            .catch((xhr) => {
                $("#msg-login-box").prepend(
                    "<div id='login-error'>手机号未注册，请重新输入</div>"
                );
                $("#phonenum").on("click", function() {
                    $("#msg-login-box").children().remove("#login-error");
                });
            });
    }
});
$("#psd-login").on("click", function() {
    username = $("#username").val();
    password = $("#password").val();
    $.ajax({
            type: "get",
            url: "../../interface/login.php",
            data: { username, password },
            dataType: "json",
        })
        .then((res) => {
            console.log(res.username);
            alert(`用户${res.username}登录成功`);
            location.href = `./index.html?username=${res.username}`;
        })
        .catch((xhr) => {
            console.log(xhr.status);
            $("#psd-login-box").prepend(
                "<div id='login-error'>登录名或登录密码不正确</div>"
            );
            $("#username").on("blur", function() {
                if (username != $("#username").val()) {
                    $("#psd-login-box").children().remove("#login-error");
                }
            });
        });
});